<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form action="">
    <input type="file" name="abcd">
    <button>上传</button>
  </form>

  <progress style="display: none;"></progress>

  <script>
    let pro = document.querySelector('progress');
    // 表单提交 --> 阻止默认行为 --> 收集数据 --> Ajax提交

    document.querySelector('form').onsubmit = function (e) {
      e.preventDefault();
      // 收集表单数据
      let fd = new FormData(this);
      // Ajax提交
      let xhr = new XMLHttpRequest();

      // 下载进度事件
      xhr.onprogress = function () { }
      // 上传进度事件
      xhr.upload.onprogress = function (e) {
        // console.log(e.loaded); // 上传了多少
        // console.log(e.total); // 文件总大小
        pro.max = e.total;
        pro.value = e.loaded;
        pro.style.display = 'block';
      }

      xhr.onload = function () {
        let res = JSON.parse(this.responseText);
        console.log(res);
      }
      xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
      xhr.send(fd);
    }
  </script>
</body>

</html>